<!--
 * @Descripttion: 背景跟随图片 变化
 * @Author: jhw
 * @Date: 2023-05-18 20:40:10
 * @LastEditors: jhw
 * @LastEditTime: 2023-05-19 20:24:53
-->
<template>
  <div id="grid" class="grid">
    <div v-for="(url, i) in images" :key="i" class="item">
      <img
        :src="url"
        crossorigin="anonymous"
        alt="图片"
        :style="{
          opacity: hoverIndex === -1 ? 1 : i === hoverIndex ? 1 : 0.2,
        }"
        @mouseenter="handleMouseEnter($event.target, i)"
        @mouseleave="handleMouseLeave"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import ColorThief from 'colorthief';

const images: any = [];
const colorthief = new ColorThief();

for (let i = 1; i <= 4; i++) {
  images.push(`https://picsum.photos/200/200?random=${i}`);
}

const hoverIndex = ref(-1);
async function handleMouseEnter(img: any, index: number) {
  hoverIndex.value = index;
  // 得到传入图片的调色盘 前三种颜色
  const color = await colorthief.getPalette(img, 3);
  console.log(color, 'color');
  // 设置背景渐变颜色
  document.getElementById(
    'grid',
  )!.style.background = `linear-gradient(to right, rgb(${color[0][0]}, ${color[0][1]}, ${color[0][2]}), rgb(${color[1][0]}, ${color[1][1]}, ${color[1][2]}), rgb(${color[2][0]}, ${color[2][1]}, ${color[2][2]}))`;
}

async function handleMouseLeave() {
  hoverIndex.value = -1;
  document.getElementById('grid')!.style.background = '#fff';
}
</script>

<style lang="scss" scoped>
.grid {
  width: 80%;
  display: flex;
  flex-wrap: wrap;
  padding: 50px;

  .item {
    width: 200px;
    margin-right: 100px;
    margin-left: 100px;
    margin-bottom: 50px;

    img {
      width: 100%;
      height: 100%;
      transition: all 0.5s;

      &:hover {
        transform: scale(1.1);
        box-shadow: 0 0 10px #000;
      }
    }
  }
}
</style>
